const express = require('express');
const https = require('https');
const fs = require('fs');
const socketIo = require('socket.io');
const bodyParser = require('body-parser');
const path = require('path');
const multer = require('multer');

// 读取配置文件
const config = require('./config/config.json');

const app = express();

// 读取 SSL 证书和私钥文件
const options = {
    key: fs.readFileSync(config.ssl.key),
    cert: fs.readFileSync(config.ssl.cert)
};

const server = https.createServer(options, app);
const io = socketIo(server);

// messages 存储所有消息,格式：[{message: 'xxx', time: 'xxx', attachment: 'xxx'}, {...}]
let messages = [];

// 设置存储引擎
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public/uploads/'); // 上传的文件将被保存到 uploads 文件夹
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname); // 使用时间戳作为文件名
    },
});

// 初始化 multer
const upload = multer({ storage: storage });

// 创建文件上传的路由
app.post('/upload', upload.single('file'), (req, res) => {
    if (!req.file) {
        return res.status(400).send('没有文件上传.');
    }
    msg = {
        message: req.body.message,
        time: new Date().toLocaleString(),
        attachment: `uploads/${req.file.filename}`
    };
    messages.push(msg);
    io.emit('message', msg);
    res.send(`文件 ${req.file.filename} 上传成功!`);
});


// 设置静态文件目录
app.use(express.static(path.join(__dirname, 'public')));

// 使用 body-parser 中间件解析 JSON 请求体
app.use(bodyParser.json());

// HTTP 接口，用于发送消息
app.post('/send-message', (req, res) => {
    const msg = req.body.message;
    if (msg) {
        msgObj = {
            message: msg,
            time: new Date().toLocaleString(),
            attachment: ''
        }
        messages.push(msgObj);
        io.emit('message', msgObj);
        res.status(200).send({ success: true, message: 'Message sent' });
    } else {
        res.status(400).send({ success: false, message: 'Message is required' });
    }
});

// 当有客户端连接时
io.on('connection', (socket) => {
    console.log('A user connected');

    // 发送当前存储的所有消息给新连接的客户端
    socket.emit('init', messages);

    // 监听客户端发送的消息
    socket.on('message', (msg) => {
        messages.push(msg);
        io.emit('message', msg);
        console.log('New message received');
        console.log(msg);
    });

    // 监听客户端删除消息的请求
    socket.on('delete', (index) => {
        if (index >= 0 && index < messages.length) {
            msg = messages[index];
            messages.splice(index, 1);
            io.emit('init', messages); // 重新发送所有消息
            // 删除本地文件
            if (msg.attachment) {
                const filePath = path.join(__dirname, 'public', msg.attachment);
                console.log(`try to delete file ${filePath}`);
                if (fs.existsSync(filePath)) {
                    fs.unlinkSync(filePath);
                    console.log('Message deleted');
                }
            }
        }
    });

    // 当客户端断开连接时
    socket.on('disconnect', () => {
        console.log('A user disconnected');
    });
});

const PORT = config.port || 3000;
server.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});